package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {

        // TODO 接口仿刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (StringUtils.isNotBlank(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                // 60s内不能再发
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        String code = RandomStringUtils.randomNumeric(6) + "_" + System.currentTimeMillis();

        // redis缓存验证码，防止同一个手机号在60s内再次发送验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, code, 10, TimeUnit.MINUTES);

        thirdPartFeignService.sendCode(phone, code);
        return R.ok();
    }

    /**
     * RedirectAttributes 模拟重定向携带数据
     *
     * @param vo
     * @param result
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result,
                         RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            /*
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                errors.put(field, defaultMessage);
             */
            Map<String, String> errors = result.getFieldErrors().stream()
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage
                    ));
//            model.addAttribute("errors", errors);

            redirectAttributes.addFlashAttribute("errors", errors);

            // Request method 'POST' not supported
            // 用户注册--、regist[post]--转发/reg.html 路径映射默认都是get方式访问的

            // 校验出错，转发到注册页
            return "redirect:http://localhost:20000/register.html";
        }

        String code = vo.getCode();
        String s = "123456";

        if (!StringUtils.isEmpty(s)) {
            if (code.equals(s.split("_")[0])) {
                // 真正注册，调用远程服务进行注册
                R regist = memberFeignService.regist(vo);
                if (regist.getCode() == 0) {
                    // 成功
                    return "redirect:/login.html";
                } else {
                    // 失败
                    Map<String, Object> errors = new HashMap<>();
                    errors.put("msg", regist.getData(new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://localhost:20000/register.html";
                }
            } else {
                Map<String, Object> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://localhost:20000/register.html";
            }
        }
        return "redirect:/login.html";
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes attributes) {
        // 远程登录
        R login = memberFeignService.login(vo);
        if (login.getCode() == 0) {
            // success
            return "redirect:http://localhost:9003";
        } else {
            // fail
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", login.getData(new TypeReference<String>() {
            }));
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://localhost:20000/login.html";
        }
    }

        /*
        发送一个请求直接跳转到一个页面
        springmvc viewcontroller；将请求和页面映射过来
     */

//    @GetMapping("/login.html")
//    public String login() {
//        return "login";
//    }

//    @GetMapping("/register.html")
//    public String register() {
//        return "reg";
//    }
}
